﻿using System; 
using Macad.Common;
using Macad.Core;
using Macad.Core.Topology;
using Macad.Interaction;
using Macad.Occt;
using SpCad.Tools;
using static Macad.Interaction.ToggleSubshapesAction;

namespace SpCad.Utils
{
    public enum FaceToEdgeType
    {
        相交,合并
    }
    public class SelectFasce:Tool
    {
        readonly Body _TargetBody;
        public FaceToEdgeType FaceToEdgeType { get; set; }= FaceToEdgeType.相交;
        public List<Subshape> shapes = new List<Subshape>();
 
        public SelectFasce(Body targetBody)
        {
            _TargetBody = targetBody;
        }
        protected override bool OnStart()
        {
            // 初始化 ToolAction，从 Face 类型中选择子形状
       

            // var toolAction = new SelectAction(SubshapeTypes.Face, _TargetBody);
            var toolAction = new SelectAction(SubshapeTypes.Face, _TargetBody,
                                                new OrSelectionFilter(new FaceSelectionFilter(FaceSelectionFilter.FaceType.Plane),
                                                                      new FaceSelectionFilter(FaceSelectionFilter.FaceType.Cone),
                                                                      new FaceSelectionFilter(FaceSelectionFilter.FaceType.Cylinder)));
            if (!StartAction(toolAction))
            {
                return false;
            }
            toolAction.Finished += ToolAction_Finished;

            // Set some UI hints
            SetHintMessage("选择面");
            SetCursor(Cursors.SelectFace);
        
            return true;
        }
 
        private void ToolAction_Finished(SelectAction sender, SelectAction.EventArgs args)
        {
            if (args.SelectedSubshapeType == SubshapeTypes.Face)
            {
                var face = TopoDS.Face(args.SelectedSubshape);
                var brepAdaptor = new BRepAdaptor_Surface(face, true);
                if (brepAdaptor.GetSurfaceType() != GeomAbs_SurfaceType.Plane && brepAdaptor.GetSurfaceType() != GeomAbs_SurfaceType.Cylinder && brepAdaptor.GetSurfaceType() != GeomAbs_SurfaceType.Cone)
                {
                    SetHintMessage("选中的面不是平面、圆柱面或圆锥面.");
                    sender.Reset();
                    return;
                }
                AddSelectShape(face);
                CommitChanges();
            }
           
        }
     
        public Color SelectColor { get; set; } = AIS_Shape_Color.SelctYell;
        
        /// <summary>
        /// 添加选择对象
        /// </summary>
        /// <param name="edg"></param>
        public void AddSelectShape(TopoDS_Face edg)
        {
            if (edg == null) return;
            var p = shapes.Find(c => c.Shape.Equals(edg));
            if (p != null)
            {
                ClearShape(p.AisShape);
                shapes.Remove(p);
                return;
            }
             var _AisShape = SetAis_Shape_Face(edg);
            shapes.Add(new Subshape { Shape = edg ,AisShape= _AisShape }); 

           
         //   FaceAction_Finished(shapes);
        }
   
        public List<TopoDS_Edge> FaceActionEdge(List<Subshape> shapes)
        {
            List< TopoDS_Face > faces=new List<TopoDS_Face>();

            foreach (var item in shapes)
            {
                faces.Add((TopoDS_Face)item.Shape);
            }
            if (faces == null || faces.Count < 2) 
            SetHintMessage("至少需要两个面来查找共有边.");
            // 存储每个面的边
            List<TopoDS_Edge> faceEdges = new List<TopoDS_Edge>();
           
            List<TopoDS_Edge> ledges = new List<TopoDS_Edge>();
            // 遍历每个面
            foreach (var face in faces)
            {
                // 获取面的边
                ledges.AddRange(face.Edges());
            }
            for (int i = 0; i < ledges.Count; i++)
            {
                var item = ledges[i];
                ledges.RemoveAt(i);
                if (ledges.Any(e => AreEdgesSame(item, e)))
                {
                    faceEdges.Add(item);
                }
                i--; // 调整索引，因为删除元素后集合大小减少
            }

            return faceEdges;
          
        }
        private bool AreEdgesSame(TopoDS_Edge edge1, TopoDS_Edge edge2)
        { 
           
            var uedge1 = ShapeTools.Create(edge1);
            var uedge2 = ShapeTools.Create(edge2);
            if (uedge1.IsEqual(uedge2))
            {
                return true;
            }
            return false;
        }
        List<TopoDS_Shape> _SubshapesOfFace;
        public void ActionEdge(List<TopoDS_Edge> shapes)
        {
         
            _SubshapesOfFace = new List<TopoDS_Shape>();
            _SubshapesOfFace.AddRange(shapes);
          var newAction = new SelectSubshapeAction(_SubshapesOfFace);
          

            if (!StartAction(newAction))
            {
                Stop();
                return;
            }
            //newAction.Preview += _SelectBaseAction_Preview;
            //newAction.Finished += _SelectBaseAction_Finished;

            SetHintMessage("请选择边框.");
            SetCursor(Cursors.SelectEdge);
            WorkspaceController.Invalidate();
        }

        #region 选择着色器
        /// <summary>
        /// 设置Face颜色
        /// </summary>
        /// <param name="edg"></param>
        /// <returns></returns>
        private AIS_Shape SetAis_Shape_Face(TopoDS_Shape edg)
        {
       
            AIS_Shape _AisShape = new AIS_Shape(edg);
            _AisShape.SetZLayer(-2); // Graphic3d_ZLayerId_Top
            _AisShape.SetColor(SelectColor.ToQuantityColor());
            _AisShape.Attributes().LineAspect().SetColor(new Color(0.0f, 0.0f, 1.0f).ToQuantityColor());
            _AisShape.SetWidth(3);
            _AisShape.Attributes().PointAspect().SetScale(3);
            InteractiveContext.Current.WorkspaceController.Workspace.AisContext.Display(_AisShape, false);
            InteractiveContext.Current.WorkspaceController.Workspace.AisContext.Deactivate(_AisShape);
         
            return _AisShape;
        }
        /// <summary>
        /// 清除选择对象
        /// </summary>
        public void ClearShape(AIS_Shape _AisShape)
        {
            if (_AisShape != null)
            {
                InteractiveContext.Current.WorkspaceController.Workspace.AisContext.Remove(_AisShape, false);
                InteractiveContext.Current.WorkspaceController.Workspace.AisContext.Erase(_AisShape, false);
                _AisShape = null;
            }
        }
        #endregion

        protected override void OnStop()
        {
            shapes.ForEach(p => {  ClearShape(p.AisShape);  });
            shapes.Clear();
          
            base.OnStop();
        }
    }
}
